﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LinqToTwitter;
using System.Linq.Expressions;

namespace TwitterWallWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void _user_Click(object sender, RoutedEventArgs e)
        {
            LoadUser(_userName.Text);
        }


        private void _hashtag_Click(object sender, RoutedEventArgs e)
        {
            LoadHashtag(_hashtagName.Text);
        }

        private void LoadUser(string username)
        {
            TwitterContext twitterCtx = new TwitterContext();

            var tweets = from tweet in twitterCtx.Status
                         where tweet.ScreenName == username &&
                               tweet.Type == StatusType.User
                         select new Tweet()
              {
                  ScreenName = tweet.ScreenName,
                  ImageUrl = tweet.User.ProfileImageUrl,
                  Text = tweet.Text
              };

            _list.ItemsSource = tweets.ToList();
        }

        private void LoadHashtag(string hashtag)
        {
            TwitterContext twitterCtx = new TwitterContext();

            var queryResults =
                from search in twitterCtx.Search
                where search.Type == SearchType.Search &&
                      search.Hashtag == hashtag &&
                      search.Page == 1 &&
                      search.PageSize == 50
                select search;

            List<Tweet> result = new List<Tweet>();
            foreach (var t in queryResults)
            {
                foreach (var e in t.Entries)
                {
                    Tweet tweet = new Tweet();
                    tweet.ScreenName = e.Author.Name;
                    tweet.ImageUrl = e.Image;
                    tweet.Text = e.Title;
                    result.Add(tweet);
                }
            }

            _list.ItemsSource = result;
        }
    }
}
